/**
 * 标题栏工具函数
 */

import { getCurrentWindow } from '@tauri-apps/api/window'
import type { 
  TitleBarTheme, 
  TitleBarThemes, 
  WindowState, 
  CustomButton,
  TitleBarUtils 
} from '@/types/titleBar'

/**
 * 预定义主题
 */
export const titleBarThemes: typeof TitleBarThemes = {
  dark: {
    backgroundColor: '#2c2c2c',
    textColor: '#ffffff',
    height: '32px',
    borderColor: 'rgba(255, 255, 255, 0.1)',
    hoverColor: 'rgba(255, 255, 255, 0.1)',
    activeColor: 'rgba(255, 255, 255, 0.2)'
  },
  light: {
    backgroundColor: '#f5f5f5',
    textColor: '#333333',
    height: '32px',
    borderColor: 'rgba(0, 0, 0, 0.1)',
    hoverColor: 'rgba(0, 0, 0, 0.05)',
    activeColor: 'rgba(0, 0, 0, 0.1)'
  },
  primary: {
    backgroundColor: '#1890ff',
    textColor: '#ffffff',
    height: '32px',
    borderColor: 'rgba(255, 255, 255, 0.2)',
    hoverColor: 'rgba(255, 255, 255, 0.1)',
    activeColor: 'rgba(255, 255, 255, 0.2)'
  },
  success: {
    backgroundColor: '#52c41a',
    textColor: '#ffffff',
    height: '32px',
    borderColor: 'rgba(255, 255, 255, 0.2)',
    hoverColor: 'rgba(255, 255, 255, 0.1)',
    activeColor: 'rgba(255, 255, 255, 0.2)'
  },
  warning: {
    backgroundColor: '#faad14',
    textColor: '#ffffff',
    height: '32px',
    borderColor: 'rgba(255, 255, 255, 0.2)',
    hoverColor: 'rgba(255, 255, 255, 0.1)',
    activeColor: 'rgba(255, 255, 255, 0.2)'
  },
  danger: {
    backgroundColor: '#ff4d4f',
    textColor: '#ffffff',
    height: '32px',
    borderColor: 'rgba(255, 255, 255, 0.2)',
    hoverColor: 'rgba(255, 255, 255, 0.1)',
    activeColor: 'rgba(255, 255, 255, 0.2)'
  }
}

/**
 * 窗口操作工具类
 */
export class WindowManager {
  private window = getCurrentWindow()

  /**
   * 获取当前窗口状态
   */
  async getWindowState(): Promise<WindowState> {
    try {
      const [isMaximized, isMinimized, isFullscreen, isVisible, isFocused] = await Promise.all([
        this.window.isMaximized(),
        this.window.isMinimized(),
        this.window.isFullscreen(),
        this.window.isVisible(),
        this.window.isFocused()
      ])

      return {
        isMaximized,
        isMinimized,
        isFullscreen,
        isVisible,
        isFocused
      }
    } catch (error) {
      console.error('Failed to get window state:', error)
      return {
        isMaximized: false,
        isMinimized: false,
        isFullscreen: false,
        isVisible: true,
        isFocused: true
      }
    }
  }

  /**
   * 最小化窗口
   */
  async minimize(): Promise<void> {
    try {
      await this.window.minimize()
    } catch (error) {
      console.error('Failed to minimize window:', error)
      throw error
    }
  }

  /**
   * 最大化窗口
   */
  async maximize(): Promise<void> {
    try {
      await this.window.maximize()
    } catch (error) {
      console.error('Failed to maximize window:', error)
      throw error
    }
  }

  /**
   * 还原窗口
   */
  async unmaximize(): Promise<void> {
    try {
      await this.window.unmaximize()
    } catch (error) {
      console.error('Failed to unmaximize window:', error)
      throw error
    }
  }

  /**
   * 切换最大化状态
   */
  async toggleMaximize(): Promise<void> {
    try {
      const isMaximized = await this.window.isMaximized()
      if (isMaximized) {
        await this.unmaximize()
      } else {
        await this.maximize()
      }
    } catch (error) {
      console.error('Failed to toggle maximize:', error)
      throw error
    }
  }

  /**
   * 关闭窗口
   */
  async close(): Promise<void> {
    try {
      await this.window.close()
    } catch (error) {
      console.error('Failed to close window:', error)
      throw error
    }
  }

  /**
   * 开始拖拽窗口
   */
  async startDragging(): Promise<void> {
    try {
      await this.window.startDragging()
    } catch (error) {
      console.error('Failed to start dragging:', error)
      throw error
    }
  }

  /**
   * 设置窗口标题
   */
  async setTitle(title: string): Promise<void> {
    try {
      await this.window.setTitle(title)
    } catch (error) {
      console.error('Failed to set window title:', error)
      throw error
    }
  }

  /**
   * 监听窗口事件
   */
  async onResized(callback: () => void) {
    try {
      return await this.window.onResized(callback)
    } catch (error) {
      console.error('Failed to listen to resize events:', error)
      throw error
    }
  }

  /**
   * 监听窗口移动事件
   */
  async onMoved(callback: () => void) {
    try {
      return await this.window.onMoved(callback)
    } catch (error) {
      console.error('Failed to listen to move events:', error)
      throw error
    }
  }

  /**
   * 监听窗口聚焦事件
   */
  async onFocusChanged(callback: () => void) {
    try {
      return await this.window.onFocusChanged(callback)
    } catch (error) {
      console.error('Failed to listen to focus events:', error)
      throw error
    }
  }
}

/**
 * 主题工具函数
 */
export const themeUtils: TitleBarUtils = {
  /**
   * 应用主题到元素
   */
  applyTheme(element: HTMLElement, theme: TitleBarTheme): void {
    if (!element || !theme) return

    element.style.setProperty('--title-bar-bg', theme.backgroundColor)
    element.style.setProperty('--title-bar-color', theme.textColor)
    element.style.setProperty('--title-bar-height', theme.height)
    
    if (theme.borderColor) {
      element.style.setProperty('--title-bar-border', theme.borderColor)
    }
    if (theme.hoverColor) {
      element.style.setProperty('--title-bar-hover', theme.hoverColor)
    }
    if (theme.activeColor) {
      element.style.setProperty('--title-bar-active', theme.activeColor)
    }
  },

  /**
   * 获取预定义主题
   */
  getTheme(themeName: keyof typeof titleBarThemes): TitleBarTheme {
    return titleBarThemes[themeName] || titleBarThemes.dark
  },

  /**
   * 创建自定义主题
   */
  createCustomTheme(
    baseTheme: keyof typeof titleBarThemes, 
    overrides: Partial<TitleBarTheme>
  ): TitleBarTheme {
    const base = this.getTheme(baseTheme)
    return { ...base, ...overrides }
  },

  /**
   * 验证主题配置
   */
  validateTheme(theme: TitleBarTheme): boolean {
    if (!theme) return false
    
    const required = ['backgroundColor', 'textColor', 'height']
    return required.every(prop => prop in theme && theme[prop as keyof TitleBarTheme])
  }
}

/**
 * 自定义按钮管理器
 */
export class CustomButtonManager {
  private buttons: Map<string, CustomButton> = new Map()

  /**
   * 添加按钮
   */
  addButton(button: CustomButton): void {
    if (!button.id) {
      throw new Error('Button must have an id')
    }
    this.buttons.set(button.id, button)
  }

  /**
   * 移除按钮
   */
  removeButton(buttonId: string): boolean {
    return this.buttons.delete(buttonId)
  }

  /**
   * 更新按钮
   */
  updateButton(buttonId: string, updates: Partial<CustomButton>): boolean {
    const button = this.buttons.get(buttonId)
    if (!button) return false

    const updatedButton = { ...button, ...updates }
    this.buttons.set(buttonId, updatedButton)
    return true
  }

  /**
   * 获取按钮
   */
  getButton(buttonId: string): CustomButton | undefined {
    return this.buttons.get(buttonId)
  }

  /**
   * 获取所有按钮
   */
  getAllButtons(): CustomButton[] {
    return Array.from(this.buttons.values())
  }

  /**
   * 获取可见按钮
   */
  getVisibleButtons(): CustomButton[] {
    return this.getAllButtons().filter(button => button.visible !== false)
  }

  /**
   * 清空所有按钮
   */
  clear(): void {
    this.buttons.clear()
  }
}

/**
 * 创建窗口管理器实例
 */
export const windowManager = new WindowManager()

/**
 * 创建按钮管理器实例
 */
export const buttonManager = new CustomButtonManager()

/**
 * 工具函数：防抖
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null
  
  return (...args: Parameters<T>) => {
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => func(...args), wait)
  }
}

/**
 * 工具函数：节流
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let lastTime = 0
  
  return (...args: Parameters<T>) => {
    const now = Date.now()
    if (now - lastTime >= wait) {
      lastTime = now
      func(...args)
    }
  }
}
